package net.xinqushi.pthread.pthreadlocal;

import net.xinqushi.utils.Reflections;

/**
 * threadLocal 内存泄漏的例子
 * 所以使用 threadLocal 需要手动调用remove防止内存泄漏
 */
public class ThreadLocalMemoryLeak {

    public static void main(String[] args) {
        leak();
        Object threadLocals = Reflections.getFieldValue(Thread.currentThread(), "threadLocals");
        Object[] table = (Object[])Reflections.getFieldValue(threadLocals, "table");
        for (Object  obj : table) {
            if(obj == null) continue;
            Object referent =  Reflections.getFieldValue(obj, "referent");
            Object value = Reflections.getFieldValue(obj, "value");
            System.out.println(referent + "  " + value);
        }


    }

    static void leak(){
        ThreadLocal<Integer> local1 = new ThreadLocal<>();
        ThreadLocal<Integer> local2 = new ThreadLocal<>();
        local1.set(1);
        local2.set(2);
        local1 = null; local2 = null;
        System.gc();
    }
}
